<template>
  <div class="article-edit-container">
    <div class="header">
      <h1>{{ isEdit ? '编辑文章' : '新建文章' }}</h1>
      <div class="header-actions">
        <a-button @click="goBack">返回</a-button>
        <a-button type="primary" @click="saveAsDraft" :loading="saving">保存草稿</a-button>
        <a-button type="primary" @click="publishArticle" :loading="publishing">发布</a-button>
      </div>
    </div>
    
    <a-form :model="articleForm" layout="vertical" class="article-form">
      <a-form-item label="标题" name="title" required>
        <a-input v-model:value="articleForm.title" placeholder="请输入文章标题" />
      </a-form-item>
      
      <a-form-item label="摘要">
        <a-textarea v-model:value="articleForm.summary" placeholder="请输入文章摘要" :rows="3" />
      </a-form-item>
      
      <a-form-item label="分类">
        <a-select v-model:value="articleForm.categoryId" placeholder="请选择分类" style="width: 200px">
          <a-select-option v-for="category in categoryStore.categories" :key="category.id" :value="category.id">
            {{ category.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      
      <a-form-item label="封面图片">
        <div class="upload-wrapper">
          <a-upload
            list-type="picture-card"
            :file-list="fileList"
            :customRequest="handleUpload"
            :maxCount="1"
            v-if="!articleForm.coverImage"
          >
            <div v-if="!articleForm.coverImage">
              <upload-outlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
          <div v-if="articleForm.coverImage" class="preview-image">
            <img :src="getStaticUrl(articleForm.coverImage)" alt="封面预览" />
            <div class="preview-actions">
              <a-button type="primary" danger size="small" @click="removeCoverImage">删除</a-button>
            </div>
          </div>
        </div>
      </a-form-item>
      
      <a-form-item label="内容" required>
        <div id="editor-container" ref="editorContainer" class="editor-container"></div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';
import { useCategoryStore } from '@/stores/category';
import { getArticleDetail, createArticle, updateArticle } from '@/api/article';
import { uploadImage } from '@/api/upload';
import { getStaticUrl } from '@/utils/url';
import Quill from 'quill';
import 'quill/dist/quill.snow.css';

// 导入完整版的 highlight.js 而不是核心版本
import hljs from 'highlight.js';
import 'highlight.js/styles/vs2015.css';

// 将 hljs 设置为全局变量，以便 Quill 可以访问
window.hljs = hljs;

const route = useRoute();
const router = useRouter();
const categoryStore = useCategoryStore();
const editorContainer = ref(null);
let quillEditor = null;

const isEdit = ref(false);
const saving = ref(false);
const publishing = ref(false);
const articleForm = ref({
  id: null,
  title: '',
  content: '',
  summary: '',
  categoryId: null,
  coverImage: '',
  status: 0
});
const fileList = ref([]);

// 初始化 Quill 编辑器
onMounted(async () => {
  // 加载分类
  if (categoryStore.categories.length === 0) {
    await categoryStore.fetchCategories();
  }
  
  // 检查是否是编辑模式
  const id = route.params.id;
  if (id) {
    isEdit.value = true;
    await loadArticleDetail(parseInt(id as string));
  }
  
  // 确保DOM已加载
  await nextTick();
  
  // 初始化Quill编辑器
  const container = editorContainer.value;
  if (container) {
    // 创建编辑器实例
    quillEditor = new Quill(container, {
      theme: 'snow',
      modules: {
        toolbar: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ 'header': 1 }, { 'header': 2 }],
          [{ 'list': 'ordered' }, { 'list': 'bullet' }],
          [{ 'script': 'sub' }, { 'script': 'super' }],
          [{ 'indent': '-1' }, { 'indent': '+1' }],
          [{ 'direction': 'rtl' }],
          [{ 'size': ['small', false, 'large', 'huge'] }],
          [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
          [{ 'color': [] }, { 'background': [] }],
          [{ 'font': [] }],
          [{ 'align': [] }],
          ['clean'],
          ['link', 'image']
        ],
      },
      placeholder: '请输入文章内容...',
    });
    
    // 设置编辑器内容变化监听
    quillEditor.on('text-change', () => {
      // 更新表单内容
      articleForm.value.content = quillEditor.root.innerHTML;
    });
    
    // 如果是编辑模式，获取文章详情
    if (isEdit.value) {
      quillEditor.root.innerHTML = articleForm.value.content;
    }
    
    // 添加图片处理器
    const toolbar = quillEditor.getModule('toolbar');
    toolbar.addHandler('image', imageHandler);
  }
});

// 加载文章详情
const loadArticleDetail = async (id) => {
  try {
    const article = await getArticleDetail(id);
    
    // 设置表单值
    articleForm.value.id = article.id;
    articleForm.value.title = article.title;
    articleForm.value.summary = article.summary || '';
    articleForm.value.categoryId = article.categoryId;
    articleForm.value.coverImage = article.coverImage || '';
    articleForm.value.status = article.status || 0;
    
    // 设置封面图片预览
    if (article.coverImage) {
      fileList.value = [
        {
          uid: '-1',
          name: '封面图片',
          status: 'done',
          url: getStaticUrl(article.coverImage)
        }
      ];
    }
    
    // 编辑器内容在编辑器初始化后设置
    if (article.content) {
      articleForm.value.content = article.content;
    }
  } catch (error) {
    console.error('加载文章详情失败', error);
    message.error('加载文章详情失败');
  }
};

// 图片处理器
const imageHandler = () => {
  const input = document.createElement('input');
  input.setAttribute('type', 'file');
  input.setAttribute('accept', 'image/*');
  input.click();
  
  input.onchange = async () => {
    const file = input.files[0];
    if (file) {
      try {
        // 创建FormData对象并添加文件
        const formData = new FormData();
        formData.append('file', file);
        
        // 上传图片
        message.loading({ content: '上传中...', key: 'imageUpload' });
        const res = await uploadImage(formData);
        message.success({ content: '上传成功', key: 'imageUpload' });
        
        // 获取光标位置并插入图片
        const range = quillEditor.getSelection();
        quillEditor.insertEmbed(range.index, 'image', getStaticUrl(res.url));
      } catch (error) {
        console.error('图片上传失败:', error);
        message.error('图片上传失败');
      }
    }
  };
};

// 上传封面图片
const handleUpload = async ({ file, onSuccess, onError }) => {
  const formData = new FormData();
  formData.append('file', file);
  
  try {
    const res = await uploadImage(formData);
    articleForm.value.coverImage = res.url;
    
    if (onSuccess) onSuccess(res);
  } catch (error) {
    console.error('上传图片失败:', error);
    if (onError) onError(error);
  }
};

// 移除封面图片
const removeCoverImage = () => {
  articleForm.value.coverImage = '';
  fileList.value = [];
};

// 保存为草稿
const saveAsDraft = async () => {
  articleForm.value.status = 0;
  await saveArticle();
};

// 发布文章
const publishArticle = async () => {
  articleForm.value.status = 1;
  await saveArticle();
};

// 保存文章
const saveArticle = async () => {
  // 表单验证
  if (!articleForm.value.title) {
    message.error('请输入文章标题');
    return;
  }
  
  if (!articleForm.value.content) {
    message.error('请输入文章内容');
    return;
  }
  
  try {
    // 根据是否有ID决定创建还是更新
    if (isEdit.value) {
      publishing.value = true;
      await updateArticle(articleForm.value.id, articleForm.value);
      message.success('文章更新成功');
    } else {
      saving.value = true;
      await createArticle(articleForm.value);
      message.success('文章保存成功');
    }
    
    // 跳转到我的文章页面
    router.push('/user/articles');
  } catch (error) {
    console.error('保存文章失败:', error);
    message.error('保存文章失败');
  } finally {
    saving.value = false;
    publishing.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};
</script>

<style scoped>
.article-edit-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.article-form {
  max-width: 100%;
}

.upload-wrapper {
  display: flex;
  align-items: center;
}

.preview-image {
  position: relative;
  width: 100px;
  height: 100px;
  margin-right: 16px;
}

.preview-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.preview-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  padding: 4px;
  text-align: center;
}

.editor-container {
  height: 400px;
  margin-bottom: 30px;
}

:deep(.ql-editor) {
  min-height: 300px;
}

:deep(.ql-snow .ql-picker.ql-header .ql-picker-label::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item::before) {
  content: '正文';
}

:deep(.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="1"]::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="1"]::before) {
  content: '标题1';
}

:deep(.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="2"]::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="2"]::before) {
  content: '标题2';
}

:deep(.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="3"]::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="3"]::before) {
  content: '标题3';
}

:deep(.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="4"]::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="4"]::before) {
  content: '标题4';
}

:deep(.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="5"]::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="5"]::before) {
  content: '标题5';
}

:deep(.ql-snow .ql-picker.ql-header .ql-picker-label[data-value="6"]::before),
:deep(.ql-snow .ql-picker.ql-header .ql-picker-item[data-value="6"]::before) {
  content: '标题6';
}
</style> 